package com.lagou.ipersistence.binding;

import com.lagou.ipersistence.session.Configuration;
import com.lagou.ipersistence.session.SqlSession;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Yan Jiahong
 * Created on 2020/11/22
 */
public class MapperRegistry {
    private final Configuration configuration;
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();
    
    public MapperRegistry(Configuration configuration) {
        this.configuration = configuration;
    }
    
    public boolean hasMapper(Class<?> type) {
        return knownMappers.containsKey(type);
    }
    
    public <T> void addMapper(Class<T> type) {
        if (type.isInterface()) {
            if (hasMapper(type)) {
                throw new BindingException("类型" + type + "已经注册到了Mapper注册器!");
            }
            knownMappers.put(type, new MapperProxyFactory<>(type));
        }
    }
    
    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("类型: " + type + "没有被注册到Mapper注册器!");
        }
        return mapperProxyFactory.newInstance(sqlSession);
    }
}
